﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ArmaModLauncher
{
    public partial class Window : Form
    {
        private Settings _settings;

        public Window()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            if(File.Exists(".\\config.cfg"))
            {
                _settings = Settings.Deserialize(".\\config.cfg");
            }
            else
            {
                _settings = new Settings();
                _settings.ParameterSettings = new LaunchParameterSettings();
            }

            // hook change event
            dataGridView1.CurrentCellDirtyStateChanged += DataGridView1OnCurrentCellDirtyStateChanged;

            // hook exit event
            Closing += (sender, args) =>
                           {
                               _settings.Serialize(".\\config.cfg");

                               if (_settings.ParameterSettings.UseBeta == CheckState.Checked)
                               {
                                   File.Delete(_settings.ModFolder + "\\ArmA2OA.exe");
                                   File.Move(_settings.ModFolder + "\\backupArmA2OA.exe", _settings.ModFolder + "\\ArmA2OA.exe");
                               }
                           };

            // manually invoke refresh on startup
            RefreshView();
        }

        public void RefreshView()
        {
            // launch options
            asdToolStripMenuItem.CheckState = _settings.ParameterSettings.NoSplash;
            showscripterrorsToolStripMenuItem.CheckState = _settings.ParameterSettings.ShowScriptErrors;
            worldToolStripMenuItem.CheckState = _settings.ParameterSettings.World;

            // select all checkbox
            checkBox2.CheckState = _settings.CheckAllState;

            // beta checkbox
            checkBox1.CheckState = _settings.ParameterSettings.UseBeta;

            // fill values into grid
            dataGridView1.Rows.Clear();
            foreach (Mod mod in _settings.ParameterSettings.Mods)
            {
                dataGridView1.Rows.Add(new object[] {mod.Selected, mod.Name, mod.Path});
            }

            // invoke mod counting
            DataGridView1OnCurrentCellDirtyStateChanged(null, null);

            // time for some ropework
            label2.Text = "Current selected game folder: " + _settings.ModFolder;
            label3.Text = "Current selected steam folder: " + _settings.SteamFolder;
        }

        private void DataGridView1OnCurrentCellDirtyStateChanged(object sender, EventArgs eventArgs)
        {
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);

            bool allTrue = true;
            bool allFalse = true;
            int count = 0;

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if ((bool) row.Cells[0].Value)
                {
                    count++;
                    foreach (Mod mod in _settings.ParameterSettings.Mods)
                    {
                        if (mod.Name == (string)row.Cells[1].Value)
                            mod.Selected = true;
                    }
                    allFalse = false;
                }
                if(!(bool) row.Cells[0].Value)
                {
                    foreach (Mod mod in _settings.ParameterSettings.Mods)
                    {
                        if (mod.Name == (string)row.Cells[1].Value)
                            mod.Selected = false;
                    }
                    allTrue = false;
                }
            }
            label1.Text = "Selected mods: " + count;

            if (dataGridView1.Rows.Count >= 1)
            {
                if (allTrue)
                {
                    checkBox2.CheckState = CheckState.Checked;
                }
                else if (allFalse)
                {
                    checkBox2.CheckState = CheckState.Unchecked;
                }
                else
                {
                    checkBox2.CheckState = CheckState.Indeterminate;
                }
            }

            dataGridView1.EndEdit();
        }

        private void FindModFolders(string rootDirectory)
        {
            DirectoryInfo root = new DirectoryInfo(rootDirectory);
            List<DirectoryInfo> candidates = root.EnumerateDirectories("*").ToList();

            _settings.ParameterSettings.Mods.Clear();
            try
            {
                foreach (DirectoryInfo candidate in candidates)
                {
                    bool found = false;
                    foreach (DirectoryInfo subFolder in candidate.EnumerateDirectories())
                    {
                        if (subFolder.Name.ToLower() == "addons")
                        {
                            found = true;
                            break;
                        }
                    }
                    if (found)
                    {
                        bool state = false;
                        foreach (DataGridViewRow row in dataGridView1.Rows)
                        {
                            if ((string)row.Cells[1].Value == candidate.Name)
                            {
                                state = (bool) row.Cells[0].Value;
                            }
                        }
                        _settings.ParameterSettings.Mods.Add(new Mod(candidate.Name, candidate.FullName, state));
                    }
                }

                List<DirectoryInfo> arma2cand = root.Parent.EnumerateDirectories("*").ToList();
                DirectoryInfo arma2 = arma2cand.Where(item => item.Name == "Arma 2").ToList()[0];
                if (arma2 != null)
                {
                    _settings.ParameterSettings.SpecialMods.Add(new Mod(arma2cand[0].Name, arma2cand[0].FullName, true));
                }
                _settings.ParameterSettings.SpecialMods.Add(new Mod("Expansion", "Expansion", true));
            }
            catch(UnauthorizedAccessException)
            {
                MessageBox.Show("Need to run this shit in admin mode m8");
                // never again
                //Process.Start(new ProcessStartInfo() {FileName = Process.GetCurrentProcess().MainModule.FileName, UseShellExecute = true, Verb = "runas"});
            }
            Console.WriteLine("Found {0} mod folders", _settings.ParameterSettings.Mods.Count);
        }

        private void clickHereToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Tough luck");
        }

        private void changeModFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            DialogResult result = dialog.ShowDialog();
            if(result == DialogResult.OK)
            {
                _settings.ModFolder = dialog.SelectedPath;
            }
            // invoke refresh
            button3_Click(null, null);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            // refresh mod list
            FindModFolders(_settings.ModFolder);

            RefreshView();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Launching: " + "steam.exe -applaunch 33930 " + _settings.ParameterSettings.CommandLine());
            Process.Start(_settings.SteamFolder + "\\steam.exe", " -applaunch 33930 " + _settings.ParameterSettings.CommandLine());
        }

        private void changeSteamFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                _settings.SteamFolder = dialog.SelectedPath;
            }
            RefreshView();
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.CheckState == CheckState.Checked)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    row.Cells[0].Value = true;
                }
            }
            else if(checkBox2.CheckState == CheckState.Unchecked)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    row.Cells[0].Value = false;
                }
            }

            // invoke mod counting
            DataGridView1OnCurrentCellDirtyStateChanged(null, null);
        }

        private void asdToolStripMenuItem_Click(object sender, EventArgs e)
        {
            switch (asdToolStripMenuItem.CheckState)
            {
                case CheckState.Checked:
                    _settings.ParameterSettings.NoSplash = CheckState.Unchecked;
                    break;
                case CheckState.Unchecked:
                    _settings.ParameterSettings.NoSplash = CheckState.Checked;
                    break;
            }
            asdToolStripMenuItem.CheckState = _settings.ParameterSettings.NoSplash;
        }

        private void showscripterrorsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            switch (showscripterrorsToolStripMenuItem.CheckState)
            {
                case CheckState.Checked:
                    _settings.ParameterSettings.ShowScriptErrors = CheckState.Unchecked;
                    break;
                case CheckState.Unchecked:
                    _settings.ParameterSettings.ShowScriptErrors = CheckState.Checked;
                    break;
            }
            showscripterrorsToolStripMenuItem.CheckState = _settings.ParameterSettings.ShowScriptErrors;
        }

        private void worldToolStripMenuItem_Click(object sender, EventArgs e)
        {
            switch (worldToolStripMenuItem.CheckState)
            {
                case CheckState.Checked:
                    _settings.ParameterSettings.World = CheckState.Unchecked;
                    break;
                case CheckState.Unchecked:
                    _settings.ParameterSettings.World = CheckState.Checked;
                    break;
            }
            worldToolStripMenuItem.CheckState = _settings.ParameterSettings.World;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            _settings.ParameterSettings.UseBeta = checkBox1.CheckState;

            if (_settings.ParameterSettings.UseBeta == CheckState.Checked)
            {
                File.Move(_settings.ModFolder + "\\ArmA2OA.exe", _settings.ModFolder + "\\backupArmA2OA.exe");
                File.Copy(_settings.ModFolder + "\\Expansion\\beta\\arma2oa.exe", _settings.ModFolder + "\\ArmA2OA.exe");
            }
            else if (_settings.ParameterSettings.UseBeta == CheckState.Unchecked)
            {
                File.Delete(_settings.ModFolder + "\\ArmA2OA.exe");
                File.Move(_settings.ModFolder + "\\backupArmA2OA.exe", _settings.ModFolder + "\\ArmA2OA.exe");
            }
        }

        private void readmeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start(Environment.CurrentDirectory + "\\readme.txt");
        }
    }
}
